<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 100px;
      height: 100px;
      background: #666;
      float: left;
      margin-right: 20px;
    }
  </style>
</head>

<body>
  <div class='botton'>1</div>
  <div class='botton'>2</div>
  <div class='botton'>3</div>
  <script>
    var divArr = document.getElementsByClassName('botton')
    console.log(divArr);
    //var错误写法
    /* for(var i=0;i<divArr.length;i++){
      divArr[i].onclick=function(){
        console.log(i);
      }
    } */
    //闭包正确写法
   /*  for (var i = 0; i < divArr.length; i++) {
      (function (index) {
        divArr[index].onclick = function () {
          console.log(index);
        }
      })(i)
    } */
    //let 正确写法
    for(let i=0;i<divArr.length;i++){
      divArr[i].onclick=function(){
        console.log(i);
      }
    }
  </script>
</body>

</html>